#include <dlfcn.h>
#include "CKRule.h"



namespace K_Engine
{
    CKRule::CKRule() : 
        m_dl(NULL),
        creo(NULL),
        delo(NULL),
        dw(NULL),
        m_strRuleName(""),
        m_strOtherParams("")
    {
    }
    
    
    CKRule::~CKRule()
    {
        if(NULL != m_dl)
        {
            dlclose(m_dl);
        }
    }
    
    
    bool CKRule::LoadLibrary(std::string rule)
    {
        std::string strRuleName= "";
        int nPos = rule.find("|");
        if(-1 != nPos)
        {//存在附加参数
            m_strRuleName = rule.substr(0, nPos);
            m_strOtherParams = rule.erase(0, nPos + 1);
        }
        else
        {
            m_strRuleName = rule;
        }
        //拼凑路径和后缀
        strRuleName += "./lib/" + m_strRuleName + ".so";
        m_dl = dlopen(strRuleName.c_str(), RTLD_LAZY);
        if(NULL == m_dl)
        {
            return false;
        }
        else
        {
            creo = (creobj)dlsym(m_dl, "GetObject");
            if(NULL == creo)
            {
                return false;
            }
            delo = (delobj)dlsym(m_dl, "DelObject");
            if(NULL == delo)
            {
                return false;
            }
            dw = (doingwork)dlsym(m_dl, "DoingWork");
            if(NULL == dw)
            {
                return false;
            }
            return true;
        }
    }
    
    
    std::string CKRule::GetRuleName()
    {
        return m_strRuleName;
    }
    
    
    void* CKRule::GetObject(std::string init)
    {
        return creo(init);
    }
    
    
    void CKRule::DeleteObject(void* obj)
    {
        delo(obj);
    }
    
    
    std::string CKRule::DoingWork(void* obj)
    {
        return dw(obj, m_strOtherParams);
    }
}
